﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Finance.IDal;
using Finance.Poco;
using Dos.ORM;
using Finance.Entity;

namespace Finance.Dal
{
    public class BillDal : BaseDal, IBillDal
    {
        public bool Save(int bankCardId, int typeId, decimal amount, string remarks, string userName, int id)
        {
            using (var tran = dbSession.BeginTransaction())
            {
                Accounts accounts = new Accounts();
                accounts.Id = id;
                accounts.BankCardId = bankCardId;
                accounts.TypeId = typeId;
                accounts.Amount = amount;
                accounts.CreateUserName = userName;
                accounts.CreateTime = DateTime.Now;
                accounts.Remarks = "";

                // 获取账目类别
                var accountType = dbSession.From<AccountsType>().Where(at => at.Id == typeId).First();
                // 更改账户余额
                var bankCard = dbSession.From<BankCard>().Where(c => c.Id == bankCardId).First();
                bankCard.Attach(EntityState.Modified);
                if (accountType.IsOut == 0)
                {
                    bankCard.Amount += -1 * accounts.Amount;
                }
                else if (accountType.IsOut == 1)
                {
                    bankCard.Amount += accounts.Amount;
                }
                else
                {
                    throw new Exception("账目类别无效");
                }
                dbSession.Save<BankCard>(tran,bankCard);

                var user = dbSession.From<User>().Where(u => u.UserName == userName).First();
                accounts.OrgId = user.OrgId.Value;

                if (id == 0)
                {
                    accounts.Attach(EntityState.Added);
                }
                else
                {
                    accounts.Attach(EntityState.Modified);
                }
                bool success = dbSession.Save<Accounts>(tran,accounts) > 0;

                tran.Commit();
                return success;
            }
        }

        public IEnumerable<Entity.ViewAccountsEntity> List(int? bankCardId, DateTime? beginDate, DateTime? endDate, int pageIndex, int pageSize, out int total)
        {
            var sql = dbSession.From<ViewAccounts>();
            if(bankCardId.HasValue)
            {
                sql.Where(a => a.BankCardId == bankCardId);
            }
            if (beginDate.HasValue)
            {
                sql.Where(a => a.CreateTime >= beginDate);
            }
            if (endDate.HasValue)
            {
                sql.Where(a => a.CreateTime < endDate);
            }

            total = sql.Count();

            var accountsList = sql.Page(pageSize, pageIndex).OrderByDescending(a=>a.CreateTime).ToList();

            return accountsList.Select(AutoMapper.Mapper.Map<ViewAccountsEntity>).ToList();
        }
    }
}
